import { useUserStore} from "../store/user";
import constants from "../utils/constants";
const userStore = useUserStore()
const header = {
  'Content-Type': 'application/json',
  'authentication': userStore.getUserToken
}

// 获取药品列表
export function getMedicineList(page,pageSize) {
  return new Promise((resolve, reject) => {
    wx.request({
        url: constants.database + `/user/drug/list?page=${page}&pageSize=${pageSize}`,
        method: 'GET',
        header: {
            'Content-Type': 'application/json',
            'authentication': userStore.getUserToken
        },
        success: (res) => {
            resolve(res); // 返回原始 res 对象
        },
        fail: (err) => {
            reject(err);
        }
    });
  });
}

// 获取药品详情
export function getDrugDetailById(id){
  return new Promise((resolve) => {
    wx.request({
      url:constants.database + `/user/drug/detail/${id}`,
      method:'GET',
      header:{
            'Content-Type': 'application/json',
            'authentication': userStore.getUserToken
        },
      success:(res) => {
        resolve(res.data)
      }
    })
  })
  
}

export function deleteMedicine(id){
  wx.request({
    url: constants.database + '/user/drug/delete',
    method:'PUT',
    data:{
      id:id
    },
    header: {
        'Content-Type': 'application/json',
        'authentication': userStore.getUserToken
    }
  })
}

export function addMedicine(medicine){
  console.log("addmedicine");
  wx.request({
    url:constants.database + '/user/drug/add',
    method:'POST',
    data:medicine,
    header:{
        'Content-Type': 'application/json',
        'authentication': userStore.getUserToken
    }
  })
}

export function saveDrugGroup(group){
  wx.request({
    url: `${constants.database}/user/category/add?ids=${group.ids}&categoryName=${encodeURIComponent(group.categoryName)}`,
    method: 'POST',
    header: {
        'Content-Type': 'application/json',
        'authentication': userStore.getUserToken
    }
});
}

export function uploadImage(tempFilePath) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      // 修改为后端接口的正确路径
      url: constants.database + '/user/common/upload', 
      filePath: tempFilePath,
      // 修改为后端接收的文件参数名
      name: 'file', 
      formData: {
        'type': 'medicine'
      },
      header: {
        'Content-Type': 'application/json',
        'authentication': userStore.getUserToken
      },
      success: (uploadRes) => {
        resolve(uploadRes.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}


export function saveDrugChange(drug){
  console.log(drug);
  wx.request({
    url:constants.database + '/user/drug/update',
    method:'PUT',
    data:drug,
    header:{
      'Content-Type': 'application/json',
      'authentication': userStore.getUserToken
    }
  })
}